package com.haowan123.qinmeiren.appota2;

import java.io.File;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;

public class DownloadService extends Service {
	private DownloadObserver observer=new DownloadObserver();
	boolean isDownloading=false;
	@Override
	public void onCreate() {
		super.onCreate();
		IntentFilter filter=new IntentFilter();
		filter.addAction(Constants.DOWNLOAD_COMPLETE_ACTION);
		registerReceiver(observer, filter);
	}
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if(intent!=null){
			if(intent.getAction().equals("DLA")){
				if(isDownloading){
					
				}else{
					new Thread(new Runnable() {
					    public void run() {
					    Log.e("perform download", "perform download pkn:"+getApplicationContext().getPackageName());
					    UIApp.getHelper().download(getApplicationContext().getPackageName(),Constants.PATH,"progressFunc","installFunc");
					    }
					}).start();
					isDownloading=true;
				}
				
				
			}
		}
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		unregisterReceiver(observer);
		super.onDestroy();
	}
	
	private class DownloadObserver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(Constants.DOWNLOAD_COMPLETE_ACTION)){
				isDownloading=false;
				if(!UIApp.canOpenfile()){
					return;
				}
				Intent sintent = new Intent(Intent.ACTION_VIEW);
		    	sintent.setDataAndType(Uri.fromFile(new File(Constants.PATH)),"application/vnd.android.package-archive");
		    	sintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		    	startActivity(sintent);
			}
		}
    	
    }
}
